package com.gable.report.common.filter;

import com.gable.report.model.User;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthorityFilter implements Filter{
	Logger logger = Logger.getLogger(AuthorityFilter.class);
	
	private FilterConfig config;

    public void init(FilterConfig config){  
          this.config = config;
    } 
	public void destroy() {  
          this.config = null;
    }  
	
    public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain){  
    	String root = ((HttpServletRequest) request).getContextPath();  
//      String basePath = request.getScheme()+"://"+request.getServerName()+ ":"+request.getServerPort()+root;
//    	ServletContext context = this.config.getServletContext();
//    	long before = System.currentTimeMillis();
//    	context.log("开始过滤... ");
    	try {
    		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            HttpSession session = httpServletRequest.getSession();
            String path = httpServletRequest.getServletPath();
            //医院端调用 放行
            if (path.indexOf("login") > -1 || path.indexOf("charts/overview/assets") > -1) {
                chain.doFilter(request, response);
            } else {
            	User user = (User) session.getAttribute("loginUser");
                if (user != null) {
                	System.out.println(user.getName() + " " + path);
                    chain.doFilter(request, response);
                } else {
                	System.out.println("未登录");
                    httpServletResponse.sendRedirect(root + "/login-error");
                }
            }
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    }	

}
